package com.common.util;

import com.common.exception.ParamsErrorException;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.Validation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.validation.groups.Default;

public class ValidatorUtil {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

     public static <T> void validate(T t) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);

        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            throw new ParamsErrorException(constraintViolation.getMessage());
        }
    }

    public static <T> void validate(T obj, String propertyName) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validateProperty(obj, propertyName, Default.class);
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            throw new ParamsErrorException(constraintViolation.getMessage());
        }
    }



//    public static <T> List<String> validate2(T t) {
//        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
//
//        List<String> messageList = new ArrayList<String>();
//        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
//            messageList.add(constraintViolation.getMessage());
//        }
//        return messageList;
//    }



//    public static <T> ValidationResult validateEntity(T obj) {
//        ValidationResult result = new ValidationResult();
//        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
//        // if( CollectionUtils.isNotEmpty(set) ){
//        if (set != null && set.size() != 0) {
//            result.setHasErrors(true);
//            Map<String, String> errorMsg = new HashMap<String, String>();
//            for (ConstraintViolation<T> cv : set) {
//                errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
//            }
//            result.setErrorMsg(errorMsg);
//        }
//        return result;
//    }
//
//    public static <T> ValidationResult validateProperty(T obj, String propertyName) {
//        ValidationResult result = new ValidationResult();
//        Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
//        if (set != null && set.size() != 0) {
//            result.setHasErrors(true);
//            Map<String, String> errorMsg = new HashMap<String, String>();
//            for (ConstraintViolation<T> cv : set) {
//                errorMsg.put(propertyName, cv.getMessage());
//            }
//            result.setErrorMsg(errorMsg);
//        }
//        return result;
//    }

}
